import urllib2
from xml.dom import minidom
class RSSItem:
    """ this is an RSS item, it contains all the RSS info like Title and Description """
    def __init__(self, title="", description="", link = "", pubDate=""):
        self.title = title
        self.description = description
        self.link = link
        self.pubDate = pubDate

class RSSReader:
    """ This is our RSS Reader """
    def __init__(self, RSSUrl):
        self.RSSUrl = RSSUrl
        self.xmldoc = self.GetXMLDocument(RSSUrl)
        if (not self.xmldoc):
            print "Error Getting XML Document!"

    def GetXMLDocument(self, RSSUrl):
        """ This function reads in a RSS URL and then retruns the XML document on success """
        url_info = urllib2.urlopen(RSSUrl)
        xmldoc = None
        if (url_info):
            xmldoc = minidom.parse(url_info)
        else:
            print "Error Getting URL"
        return xmldoc

    def GetItems(self):
        """ Generator to get items """
        for channel_node in self.xmldoc.documentElement.childNodes:
            if (channel_node.nodeName == "channel"):
                for nodeItem in channel_node.childNodes:
                    if (nodeItem.nodeName == "item"):
                        """ Great, we have a item """
                        rss_item = self.CreateRSSItem(nodeItem)
                        yield rss_item

    def CreateRSSItem(self, item_node):
        """ Create an RSS Item and return it """
        title = self.GetChildText(item_node, "title")
        description = self.GetChildText(item_node, "description")
        link = self.GetChildText(item_node, "link")
        pubDate = self.GetChildText(item_node, "pubDate")
        return RSSItem(title, description, link, pubDate)

    def GetItemText (self, xml_node):
        """ Get the text from an xml item """
        text = ""
        for text_node in xml_node.childNodes:
            #if (text_node.nodeType == Node.TEXT_NODE):
            text += text_node.nodeValue
        k = text.encode('utf-8')
        return k

    def GetChildText(self, xml_node, child_name):
        """ Get a child node from the xml node """
        if (not xml_node):
            print "Error GetChildNode: No xml_node"
            return ""
        for item_node in xml_node.childNodes:
            if (item_node.nodeName == child_name):
                return self.GetItemText(item_node)
        return ""

def getDetails(url):
    if (len(str(url)) == 0):
        return ""
    try:
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        html = response.read()
    except:
        html = ""
    finally:
        response.close()
    return html